package com.py.article.service.impl;

import com.py.article.service.ArticleCollectionBehaviorService;
import com.py.common.redis.CacheService;
import com.py.model.article.dtos.CollectionBehaviorDto;
import com.py.model.common.dtos.ResponseResult;
import com.py.utils.common.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName ArticleCollectionBehaviorServiceImpl
 * @Description TODO
 * @Author AXing
 * @Date 2022/11/17 13:49
 * @Version 1.0
 */
@Service
@Slf4j
public class ArticleCollectionBehaviorServiceImpl implements ArticleCollectionBehaviorService {
    @Autowired
    private CacheService cacheService;
    /**
     * 用户收藏文章
     * @param dto
     * @return
     */
    @Override
    public ResponseResult collectionArticle(CollectionBehaviorDto dto) {
        //用户id
        Integer userId = ApUserThreadLocalUtil.get().getId();
        String collectionKey = dto.getEntryId() + "";
        String uCollectionKey = dto.getEntryId() + "_" + userId;
        String collections = (String) cacheService.hGet(collectionKey, "collections");
        if (collections == null){
            //初始化
            cacheService.hPut(collectionKey, "collections", "0");
        }
        String uCollection = (String) cacheService.hGet(uCollectionKey, "collection");
        if (uCollection == null){
            //初始化用户收藏--->0未收藏，1、收藏
            cacheService.hPut(uCollectionKey, "collection", "0");
        }
        uCollection = (String) cacheService.hGet(uCollectionKey, "collection");
        if (dto.getType() == 0){
            if (dto.getOperation() == 0 && "0".equals(uCollection)){
                //文章收藏
                log.info("收藏文章");
                cacheService.hIncrBy(collectionKey, "collections", 1);
                cacheService.hPut(uCollectionKey, "collection", "1");
            } else if (dto.getOperation() == 1 && "1".equals(uCollection)) {
                //取消文章收藏
                log.info("取消收藏文章");
                cacheService.hIncrBy(collectionKey, "collections", -1);
                cacheService.hPut(uCollectionKey, "collection", "0");
            }
        } else {
            //TODO:动态收藏
            return null;
        }
        return ResponseResult.okResult(null);
    }
}
